package com.jsnj33.pdaproject.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.jsnj33.pdaproject.R;
import com.jsnj33.pdaproject.bean.InspectionBean;
import com.jsnj33.pdaproject.constant.Constants;
import com.jsnj33.pdaproject.utils.StringUtility;
import com.jsnj33.pdaproject.utils.ToastUtil;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class BindActivity extends AppCompatActivity {
    private final static String SCAN_ACTION = ScanManager.ACTION_DECODE;//default action
    private static final String TAG = "BindActivity";
    private Vibrator mVibrator;
    private ScanManager mScanManager;
    private SoundPool soundpool = null;
    private int soundid;
    private boolean isScaning = false;
    TextView tvXaingHao;
    TextView tvZhilindan;
    TextView title;
    ImageView iv_back;
    Button btnBind;
    Button btnReBind;
    String state = "";
    LinearLayout llBind;
    TextView tvbangding;
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            isScaning = false;
            soundpool.play(soundid, 1, 1, 0, 0, 1);
            mVibrator.vibrate(100);

            byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
            int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
            byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
            String str = new String(barcode, 0, barcodelen);
            Log.i(TAG, "onReceive: " + str);

            if (StringUtility.isEmpty(str)) {
                ToastUtil.showGravityToast(BindActivity.this, "扫码失败！", Gravity.CENTER, 0, 0);
                return;
            }
            String sbs = str.substring(0, 2);
            switch (sbs) {
                //扫描货品码
                case "MO":
                    //作为制令单处理
                    tvZhilindan.setText(str);
                    break;
                default:
                    tvXaingHao.setText(str);
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_bind);
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        tvXaingHao = findViewById(R.id.tvXaingHao);
        llBind = findViewById(R.id.llBind);
        tvbangding = findViewById(R.id.tvbangding);
        title = findViewById(R.id.title);
        iv_back = findViewById(R.id.iv_back);
        tvZhilindan = findViewById(R.id.tvZhilindan);
        btnBind = findViewById(R.id.btnBind);
        btnReBind = findViewById(R.id.btnReBind);
        initData();
    }

    private void initData() {
        state = getIntent().getStringExtra("state");
        if (state.equals("bind")) {
            btnBind.setText("绑定");
            title.setText("箱码绑定");
        } else {
            btnBind.setText("查询");
            title.setText("箱码查询");
        }
        btnBind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tvZhilindan.getText().toString()) || TextUtils.isEmpty(tvXaingHao.getText().toString())) {
                    ToastUtil.showLongToast(BindActivity.this, "信息不全");
                    return;
                }
                if (state.equals("bind")) {
                    bind(tvXaingHao.getText().toString(), tvZhilindan.getText().toString());
                } else {
                    look(tvXaingHao.getText().toString(), tvZhilindan.getText().toString());
                }
            }
        });
        btnReBind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvXaingHao.setText("");
                tvZhilindan.setText("");
                llBind.setVisibility(View.GONE);
            }
        });
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initScan();
        IntentFilter filter = new IntentFilter();
        int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
        String[] value_buf = mScanManager.getParameterString(idbuf);
        if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
            filter.addAction(value_buf[0]);
        } else {
            filter.addAction(SCAN_ACTION);
        }

        registerReceiver(mScanReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mScanManager != null) {
            mScanManager.stopDecode();
            isScaning = false;
        }
        unregisterReceiver(mScanReceiver);
    }

    private void initScan() {
        mScanManager = new ScanManager();
        mScanManager.openScanner();

        mScanManager.switchOutputMode(0);
        soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
        soundid = soundpool.load("/etc/Scan_new.ogg", 1);
    }

    /**
     * 绑定箱子号
     *
     * @param xiangzihao
     * @param zhilindan
     */
    public void bind(String xiangzihao, String zhilindan) {
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Constants.SCANNING_XINAGMABIND;
        Log.i(TAG, "bind: URL=" + url);
        final Map<String, String> map = new HashMap<String, String>();
        map.put("mo_id", zhilindan);
        map.put("box_id", xiangzihao);
        JSONObject params = new JSONObject(map);
        Log.i(TAG, "bind: " + params.toString());
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                if (Integer.valueOf(response.opt("respCode").toString()) == 1) {
                    ToastUtil.showLongToast(BindActivity.this
                            , "绑定成功");
                } else {
                    ToastUtil.showLongToast(BindActivity.this, "绑定失败");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i(TAG, "onErrorResponse: " + error.getMessage());
                ToastUtil.showLongToast(BindActivity.this, "服务器异常");
            }
        });
        queue.add(jsonObjectRequest);
    }

    /**
     * 查询箱码
     *
     * @param xiangzihao
     * @param zhilindan
     */
    public void look(String xiangzihao, String zhilindan) {
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Constants.SCANNING_XINAGMALOOK;
        final Map<String, String> map = new HashMap<String, String>();
        map.put("mo_id", zhilindan);
        map.put("box_id", xiangzihao);
        JSONObject params = new JSONObject(map);
        Log.i(TAG, "look: URL=" + url);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.i(TAG, "onResponse: " + response.toString());
                if (Integer.valueOf(response.opt("respCode").toString()) == 1) {
                    ToastUtil.showLongToast(BindActivity.this, "这是正确的箱号");
                    llBind.setVisibility(View.GONE);
                } else {
                    ToastUtil.showLongToast(BindActivity.this, "箱号有误");
                    tvbangding.setText(response.optString("respMsg"));
                    llBind.setVisibility(View.VISIBLE);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i(TAG, "onErrorResponse: " + error.getMessage());
                ToastUtil.showLongToast(BindActivity.this
                        , "服务器异常");
            }
        });
        queue.add(jsonObjectRequest);
    }
}
